import React from "react";
import { autorun } from "mobx";
import { Observer } from "mobx-react-lite";
import { useRouteMatch, useLocation, useHistory } from "react-router";
import { DockedAppContainer, DialogAppContainer, DrawerAppContainer, Workbench } from "@anyshare/components";
import { useAppContainerManager, useLanguage } from "@anyshare/common/lib/hooks";
import { useEffect } from "react";
import { ipcRenderer, remote } from "electron";

export default function AppPage() {
    const appContainerManager = useAppContainerManager();
    const {
        params: { app, slash },
    } = useRouteMatch<{ app: string; slash: string }>();
    const { search } = useLocation();
    const history = useHistory();
    const language = useLanguage();

    useEffect(() => {
        appContainerManager.start(`${app}/${slash || ""}${search}`, { type: "docked" });
        Object.assign(window, { appContainerManager });
    }, [app, slash, search, appContainerManager]);

    useEffect(() => {
        ipcRenderer.send("appwindowready", remote.getCurrentWindow().id);
    }, []);

    useEffect(
        () =>
            autorun(() => {
                if (appContainerManager.lastFocusedDockedContainer) {
                    const url = `/${language.language}/${appContainerManager.lastFocusedDockedContainer.url}`;
                    if (url !== `${history.location.pathname}${history.location.search}`) {
                        history.push(url);
                    }
                }
            }),
        [appContainerManager.lastFocusedDockedContainer, history, language.language]
    );

    return (
        <Workbench>
            <Observer>
                {() => {
                    return (
                        <>
                            {appContainerManager.containers.map((container) => {
                                switch (container.type) {
                                    case "docked":
                                        return <DockedAppContainer key={container.id} container={container} />;
                                    case "dialog":
                                        return <DialogAppContainer key={container.id} container={container} />;
                                    case "drawer":
                                        return <DrawerAppContainer key={container.id} container={container} />;
                                    default:
                                        return null;
                                }
                            })}
                        </>
                    );
                }}
            </Observer>
        </Workbench>
    );
}
